package com.xie.authority_system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xie.authority_system.config.qiniu.QiniuConfig;
import com.xie.authority_system.dto.UserRoleDTO;
import com.xie.authority_system.entity.Role;
import com.xie.authority_system.entity.User;
import com.xie.authority_system.service.RoleService;
import com.xie.authority_system.service.UserService;
import com.xie.authority_system.utils.Result;
import com.xie.authority_system.utils.SystemConstants;
import com.xie.authority_system.vo.query.UserQueryVo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author 谢金成
 * @date 2024/1/8 14:59
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private QiniuConfig qiniuConfig;

    @Resource
    private RoleService roleService;

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:select')")
    public Result list(UserQueryVo userQueryVo) {
        IPage<User> page = new Page<User>(userQueryVo.getPageNo(), userQueryVo.getPageSize());
        page = userService.findUserListByPage(page, userQueryVo);
        return Result.ok(page);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public Result add(@RequestBody User user) {
        User item = userService.findUserByUserName(user.getUsername());
        if (item != null) {
            return Result.error().message("该用户名称已被使用, 请重新输入!");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if (ObjectUtils.isEmpty(user.getAvatar())) {
            user.setAvatar(qiniuConfig.getDomain() + SystemConstants.DEFAULT_AVATAR);
        }
        if (userService.save(user)) {
            return Result.ok().message("用户添加成功!");
        }

        return Result.error().message("用户添加失败!");
    }

    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    public Result update(@RequestBody User user) {
        User item = userService.findUserByUserName(user.getUsername());
        if (item != null && !Objects.equals(item.getId(), user.getId())) {
            Result.error().message("用户名称已被占用!");
        }
        if (userService.updateById(user)) {
            return Result.ok().message("用户修改成功!");
        }

        return Result.error().message("用户修改失败!");
    }

    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@PathVariable Long id) {
        if (userService.deleteById(id)) {
            return Result.ok().message("用户删除成功!");
        }

        return Result.error().message("用户删除失败!");
    }

    @GetMapping("/getRoleList")
    @PreAuthorize("hasAuthority('sys:user:assign')")
    public Result getRoleList() {
        List<Role> roleList = roleService.list();
        return Result.ok(roleList);
    }

    @GetMapping("/getUserRole/{id}")
    @PreAuthorize("hasAuthority('sys:user:assign')")
    public Result getUserRole(@PathVariable Long id) {
        return Result.ok(userService.getUserRole(id));
    }


    @PostMapping("/saveRoleAssign")
    @PreAuthorize("hasAuthority('sys:user:assign')")
    public Result saveUserRole(@RequestBody UserRoleDTO userRoleDTO) {
        if (userService.saveUserRole(userRoleDTO.getUserId(), userRoleDTO.getRoleIds())) {
            return Result.ok().message("角色分配成功!");
        }

        return Result.error().message("角色分配失败!");
    }
}
